package com.coursehub.course.repository;

import com.coursehub.course.entity.CourseStudent;
import com.coursehub.course.entity.CourseStudentId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 课程学生关联数据访问层
 */
@Repository
public interface CourseStudentRepository extends JpaRepository<CourseStudent, CourseStudentId> {
    
    /**
     * 根据课程ID查找所有课程学生关联
     */
    List<CourseStudent> findByCourse_CourseId(String courseId);
    
    /**
     * 根据用户ID查找所有课程学生关联
     */
    List<CourseStudent> findById_UserId(String userId);
    
    /**
     * 根据课程ID和用户ID查找课程学生关联
     */
    Optional<CourseStudent> findById_CourseIdAndId_UserId(String courseId, String userId);
    
    /**
     * 检查学生是否选修了该课程
     */
    boolean existsById_CourseIdAndId_UserId(String courseId, String userId);
    
    /**
     * 检查课程学生关联是否存在（自定义查询）
     */
    @Query("SELECT EXISTS(SELECT cs FROM CourseStudent cs WHERE cs.id.courseId = :courseId AND cs.id.userId = :userId)")
    boolean existsByCourseIdAndUserId(@Param("courseId") String courseId, @Param("userId") String userId);
    
    /**
     * 根据课程ID获取所有学生ID
     */
    @Query("SELECT cs.id.userId FROM CourseStudent cs WHERE cs.id.courseId = :courseId")
    List<String> findStudentIdsByCourseId(@Param("courseId") String courseId);
    
    /**
     * 根据用户ID获取所有课程ID
     */
    @Query("SELECT cs.id.courseId FROM CourseStudent cs WHERE cs.id.userId = :userId")
    List<String> findCourseIdsByUserId(@Param("userId") String userId);
}